package com.xunqi.mall.controller;

import com.xunqi.mall.consts.MallConst;
import com.xunqi.mall.enums.ResponseEnum;
import com.xunqi.mall.exception.UserLoginException;
import com.xunqi.mall.form.UserLoginForm;
import com.xunqi.mall.form.UserRegisterForm;
import com.xunqi.mall.service.UserService;
import com.xunqi.mall.vo.ResponseVo;
import com.xunqi.mall.vo.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @Description:
 * @Created with IntelliJ IDEA.
 * @author: 夏沫止水
 * @create: 2020-04-23 17:14
 **/
@RestController
@Slf4j
public class UserController {

    @Resource
    private UserService userService;


    @PostMapping(value = "/user/login")
    public ResponseVo<UserLoginVo> login(@Valid @RequestBody UserLoginForm form,
                                         //BindingResult bindingResult,
                                         HttpServletRequest request) {
        //将用户信息查询出来，保存到session中
        ResponseVo<UserLoginVo> loginResponseVo = userService.login(form);
        request.getSession().setAttribute(MallConst.CURRENT_USER,loginResponseVo.getData());

        return loginResponseVo;
    }



    @PostMapping(value = "/user/register")
    public ResponseVo register(@Valid @RequestBody UserRegisterForm form,
                               BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return ResponseVo.error(ResponseEnum.PARAM_ERROR,bindingResult);
        }

        ResponseVo registerResponseVo = userService.register(form);

        return registerResponseVo;
    }


    @GetMapping(value = "/user")
    public ResponseVo<UserLoginVo> users(HttpServletRequest request) {
        //获取当前用户登录信息
        UserLoginVo user = (UserLoginVo) request.getSession().getAttribute(MallConst.CURRENT_USER);

        ResponseVo<UserLoginVo> users = userService.users(user.getId());

        return users;
    }


    @PostMapping(value = "/user/logout")
    public ResponseVo logout(HttpServletRequest request) {
        //获取当前用户登录信息
        UserLoginVo user = (UserLoginVo) request.getSession().getAttribute(MallConst.CURRENT_USER);

        if (user == null) {
            throw new UserLoginException();
        }

        //清除session的用户值
        request.getSession().removeAttribute(MallConst.CURRENT_USER);

        return ResponseVo.success();

    }

}
